def find(nums, target):
    """

    Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0?
    Find all unique triplets in the array which gives the sum closest to target.

    Note:
    Elements in a triplet (a,b,c) must be in non-descending order.
    (ie, a ≤ b ≤ c)
    The solution set must not contain duplicate triplets.

    For example, given array S = {-1 0 1 2 -1 -4}, target = 4

    A solution set is:
    (0, 1, 2)

    :type nums: List[int]
    :rtype: List[int]
    """

    length = len(nums);
    if length < 3:
        print('No enough nums!');
        return None;

    print('Origin:', nums);
    # sort in ascending order
    for i in range(0, length - 1):
        swapped = False;
        for j in range(0, length - i - 1):
            if nums[j] > nums[j + 1]:
                temp = nums[j];
                nums[j] = nums[j + 1];
                nums[j + 1] = temp;
                swapped = True;

        if not swapped:
            break;

    # Traverse to find result
    print('Sorted:', nums);

    result = [nums[0], nums[1], nums[2]];
    closest = abs(nums[0] + nums[1] + nums[2] - target);

    for i in range(0, length - 2):
        if nums[i] > abs(target):
            break;

        for j in range(i + 1, length - 1):
            sum2 = nums[i] + nums[j];
            if sum2 > abs(target):
                break;

            for k in range(j + 1, length):
                sum3 = nums[i] + nums[j] + nums[k];
                dist = sum3 - target;
                if dist == 0:
                    result.clear();
                    result.extend([nums[i], nums[j], nums[k]]);
                    return result;
                elif dist > closest:
                    break;
                else:
                    if abs(dist) < closest:
                        result.clear();
                        result.extend([nums[i], nums[j], nums[k]]);

    return result;
